package cn.jaye.fabric.controller;

import cn.jaye.fabric.application.ApiApplicationService;
import cn.jaye.fabric.application.command.ListApiCommand;
import cn.jaye.fabric.common.constant.Global;
import cn.jaye.fabric.common.constant.MicroConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import cn.jaye.fabric.common.constant.ExceptionEnum;
import cn.jaye.fabric.common.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author Jaye
 * @create 2017-12-28 14:43
 */
@RestController
@RequestMapping("/api")
public class APIController {

    @Autowired
    private ApiApplicationService apiApplicationService;

    @Autowired
    private MicroConstant microConstant;

    @RequestMapping("/list")
    public String listApi(HttpServletRequest request) {
        Map<String, String[]> maps = request.getParameterMap();
        JSONObject requstParam = JSON.parseObject(request.getParameter("aodata"));
        int sEcho = requstParam.getIntValue("sEcho");
        String sSearch = requstParam.getString("sSearch");//查询条件
        Integer start = requstParam.getInteger("iDisplayStart");
        Integer length = requstParam.getInteger("iDisplayLength");
        Integer currentPage;
        currentPage = (start / length) + 1;
        Map<String, Object> map = new HashMap<>();
        map.put("aaData", new ArrayList<>());
        map.put("iTotalDisplayRecords", 0);
        map.put("iTotalRecords", 0);
        map.put("sEcho", sEcho + 1);
        ListApiCommand listApiCommand = new ListApiCommand();
        listApiCommand.setSizes(length);
        listApiCommand.setCurrentPage(currentPage);
        if (StringUtils.isNotBlank(sSearch)) {
            listApiCommand.setCondition(sSearch);
        }
        JSONObject jsonObject = apiApplicationService.listApi(listApiCommand);
        if (Global.SUCCESS_FLAG.equals(jsonObject.getInteger("code"))) {
            JSONObject resObject = jsonObject.getJSONObject("data");
            JSONArray jsonArray = resObject.getJSONArray("records");
            if (jsonArray.size() > 0) {
                List<Map> r = jsonArray.toJavaList(Map.class);
                map.put("aaData", r);
                map.put("iTotalDisplayRecords", resObject.getInteger("total"));
                map.put("iTotalRecords", resObject.getInteger("total"));
                map.put("sEcho", sEcho + 1);
            }
        }
        return JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
    }

    @PostMapping("/list/all")
    public String listAllApis() {
        String retData = apiApplicationService.listAllApi();
        JSONObject jsonObject = JSON.parseObject(retData);
        if (Global.SUCCESS_FLAG.equals(jsonObject.getInteger("code"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            return JSONObject.toJSONString(jsonArray);
        }
        return null;
    }

    @PostMapping("/list/test")
    public String listApiTest(@RequestBody String data) {
        List<List<String>> reult = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            List<String> dat = new ArrayList<>();
            dat.add("id_" + i);
            dat.add("no_" + i);
            dat.add("name_" + i);
            dat.add("/url/" + i);
            dat.add("serviceid_" + i);
            dat.add("serviceName_" + i);
            reult.add(dat);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", reult);
        return JSON.toJSONString(map);
    }

    @PostMapping("/import")
    public String importApi(StandardMultipartHttpServletRequest multiRequest) {
        String serviceId = multiRequest.getParameter("service_id");
        String serviceName = multiRequest.getParameter("service_name");

        //获取multiRequest 中所有的文件名
        Iterator iter = multiRequest.getFileNames();

        while (iter.hasNext()) {
            //一次遍历所有文件
            MultipartFile file = multiRequest.getFile(iter.next().toString());
            if (file != null) {
                String path = microConstant.getRamlPath() + file.getOriginalFilename();
                //上传
                try {
                    file.transferTo(new File(path));
                    return apiApplicationService.importRaml(serviceId, new File(path));
                } catch (Exception e) {
                    System.out.println("上传文件发生错误");
                }
            }
        }
        return ResultUtil.error(ExceptionEnum.API_IMPORT_FAILED);
    }
}
